// 轮询
// task [promise] 调用的方法，任务
// callback [function] 回调方法
// calintervallback [number] 间隔时间
export default function Polling(task, callback, interval) {
  this.task = task;
  this.callback = callback;
  this.interval = interval || 5000;
  this.timers = {};
  this.timerId = 0;
}

Polling.prototype.start = function() {
  this.stop();
  const id = this.timerId++;
  this.timers[id] = true;
  const fn = () => {
    if (this.timers[id]) {
      this.task()
        .then(this.callback)
        .finally(() => {
          setTimeout(fn, this.interval);
        });
    }
  };
  fn();
};
Polling.prototype.stop = function() {
  this.timers = {};
};

// 方式二
// const polling = {
//   timerId: 0,
//   timers: {},
//   start(task, callback) {
//     this.stop();
//     const id = this.timerId++;
//     this.timers[id] = true;
//     const fn = () => {
//       if (this.timers[id]) {
//         task()
//           .then(callback)
//           .finally(() => {
//             setTimeout(fn, 2000);
//           });
//       }
//     };
//     fn();
//   },
//   stop() {
//     this.timers = {};
//   }
// };
